<script setup name="customer">
import Form from './form.vue'
import {
  GetListAPI,
  AddDataAPI,
  EditDataAPI,
  DelDataAPI,
  GetDetailAPI,
  FrozenAPI,
  ThawAPI,
  RevokeAPI,
  ToExamineAPI,
  ReviewSubmitAPI
} from '@/api/order/subcontracting/converter'
const { proxy } = getCurrentInstance()

// 封装 方法 字典查询
const {
  customer_level, // 等级
  customer_affiliated_organization //所属机构
} = proxy.useDict('customer_level', 'customer_affiliated_organization')

const FormOneRef = ref(null)

// 新增弹窗状态
const addIsShow = ref(false)

// 审核弹窗状态
const examineIsShow = ref(false)

// 标题
const title = ref('新增')

// 保存加载状态
const Btnloading = ref(false)

// 表格加载状态
const loading = ref(false)

// 表格数据
const TableData = ref([])

// 列表总数量
const total = ref(0)

// 是否禁用删除
const DelDisabled = ref(false)

// 是否禁用 单选
const ExamineDisabled = ref(false)

//
const Ids = ref([])
const rows = ref([])
const importShow = ref(false)
// 查询条件
const SelectList = ref([
  // { type: '日期范围' },
  { label: '加工商编号', model: 'converterNum', type: '输入框', placeholder: '请输入加工商编号' },
  { label: '加工商名称', model: 'converterName', type: '输入框', placeholder: '请输入加工商名称' }
])

// 新增字段
const ruleForm = reactive({
  affiliatedOrganization: '', // 所属机构
  converterName: '', // 加工商名称
  converterAbbreviation: '', // 加工商简称
  converterLevel: '', // 加工商等级
  converterAddress: '', // 加工商地址
  invoicingInformation: '', //开票信息
  businessLicense: '', //营业执照
  contactsBy: '', // 联系人
  contactsInformation: '', // 联系方式
  ascriptionBy: '', // 归属人
  remark: '' // 备注
})

// 查询条件
const query = reactive({
  pageNum: 1,
  pageSize: 10
})

/**
 * 弹窗
 */
const add = () => {
  title.value = '新增'
  addIsShow.value = true
}

const edit = async id => {
  try {
    proxy.$modal.loading('请稍后')
    title.value = '修改'
    const res = await GetDetailAPI(id)
    for (let Key in res.data) {
      ruleForm[Key] = res.data[Key]
    }
    addIsShow.value = true
  } catch {
  } finally {
    proxy.$modal.closeLoading()
  }
}

// 列表选中 及 判断是否禁用删除 || 修改
const handleSelectionChange = selection => {
  rows.value = selection
  Ids.value = selection.map(item => item.id)
  DelDisabled.value = !selection.length
  selection.length <= 0 || selection.length > 1 ? (ExamineDisabled.value = true) : (ExamineDisabled.value = false)
}
handleSelectionChange([])

// 新增
const addSub = async () => {
  try {
    const isif = await FormOneRef.value.submit()
    if (!isif) return
    Btnloading.value = true
    const res = await AddDataAPI(isif)
    if (res.code !== 200) return
    proxy.successMsg('新增成功')
    addClose()
  } catch {
  } finally {
    Btnloading.value = false
  }
}

// 修改
const EditSub = async () => {
  try {
    const isif = await FormOneRef.value.submit()
    if (!isif) return
    Btnloading.value = true
    const res = await EditDataAPI(isif)
    if (res.code !== 200) return
    addClose()
    proxy.successMsg('修改成功')
  } catch {
  } finally {
    Btnloading.value = false
  }
}

// 审核
const examine = async val => {
  const Obj = rows.value[0]
  if (Obj.auditStatus != 2) return proxy.warningMsg('此操作仅为待审核状态可用')
  proxy.$modal.loading('请稍后')
  try {
    title.value = '审核'
    const res = await GetDetailAPI(Obj.id)
    // if (res.code !== 200) return (Btnloading.value = false)
    for (let Key in res.data) {
      ruleForm[Key] = res.data[Key]
    }
    // 审核弹窗
    examineIsShow.value = true
  } catch (err) {
    // console.log(err)
  } finally {
    proxy.$modal.closeLoading()
  }
}

// 审核同意 || 不同意  （同意1 不同意 2
const yesAndNo = async val => {
  const isif = await FormOneRef.value.submit()
  if (!isif) return
  try {
    Btnloading.value = true
    const form = {
      reviewComments: isif.reviewComments,
      id: Ids.value[0],
      isAdopt: val
    }
    await ToExamineAPI(form)
    examineIsShow.value = false
    getList()
    proxy.successMsg('操作成功')
  } catch {
  } finally {
    Btnloading.value = false
  }
}
// 提交审核
const subExamine = async () => {
  const Obj = rows.value[0]
  // console.log(Obj.auditStatus)
  if (Obj.auditStatus != 1) return proxy.warningMsg('此操作仅对待提交状态可用')
  const MesBox = await proxy.FreezMessageBox('是否确定提交审核？')
  if (!MesBox) return
  const res = await ReviewSubmitAPI(Ids.value[0])
  if (res.code !== 200) return (BtnLoading.value = false)
  proxy.successMsg('操作成功')
  getList()
}

// 撤销审核
const revoke = async () => {
  const Obj = rows.value[0]
  if (Obj.auditStatus != 2) return proxy.warningMsg('此操作仅对待审核状态可用')

  const MesBox = await proxy.MessageBox('是否确定撤销审核？')
  if (!MesBox) return
  const res = await RevokeAPI(Ids.value[0])
  if (res.code !== 200) return (BtnLoading.value = false)
  proxy.successMsg('操作成功')
  getList()
}

// 封存
const frozen = async () => {
  const Obj = rows.value[0]
  if (Obj.auditStatus != 4) return proxy.warningMsg('此操作仅对已启用状态可用')

  if (Ids.value.length > 1) return proxy.warningMsg('每次只能封存一条数据')
  const MesBox = await proxy.FreezMessageBox('是否确定封存？')
  if (!MesBox) return
  const res = await FrozenAPI(Ids.value[0])
  if (res.code !== 200) return (BtnLoading.value = false)
  proxy.successMsg('操作成功')
  getList()
}

// 解冻
const thaw = async () => {
  const Obj = rows.value[0]
  if (Obj.auditStatus != 6) return proxy.warningMsg('此操作仅对已冻结状态可用')
  if (Ids.value.length > 1) return proxy.warningMsg('每次只能解冻一条数据')
  const MesBox = await proxy.FreezMessageBox('是否确定解冻？')
  if (!MesBox) return
  const res = await ThawAPI(Ids.value[0])
  if (res.code !== 200) return (BtnLoading.value = false)
  proxy.successMsg('操作成功')
  getList()
}

// 删除
const del = async val => {
  const MesBox = await proxy.DelMessageBox()
  if (!MesBox) return
  const res = await DelDataAPI(Ids.value.length <= 0 ? val : Ids.value.join(','))
  if (res.code !== 200) return (BtnLoading.value = false)
  addClose()
  proxy.successMsg('删除成功')
}

// 查看
const dxamine = async val => {
  try {
    proxy.$modal.loading('请稍后')
    title.value = '查看'
    rows.value = [val]
    const res = await GetDetailAPI(val.id)
    for (let Key in res.data) {
      ruleForm[Key] = res.data[Key]
    }
    examineIsShow.value = true
  } catch {
  } finally {
    proxy.$modal.closeLoading()
  }
}

// 新增修改弹窗关闭时
const addClose = () => {
  addIsShow.value = false
  for (let KEY in ruleForm) {
    ruleForm[KEY] = ''
  }
  getList()
}

// 新增修改弹窗关闭时
const examineClose = () => {
  examineIsShow.value = false
  for (let KEY in ruleForm) {
    query[KEY] = ''
  }
  getList()
}

// 条件查询
const selectSubmit = Obj => {
  for (let KEY in Obj) {
    query[KEY] = Obj[KEY]
  }
  getList()
}

// 获取列表
const getList = async () => {
  loading.value = true
  try {
    const res = await GetListAPI(query)
    total.value = res.total
    TableData.value = res.rows
    loading.value = false
  } catch (error) {
    loading.value = false
  } finally {
    loading.value = false
  }
}
getList()

const tableHeight = ref(0)

const maxHeight = computed(() => {
  const windowHeight = window.innerHeight
  const headerHeight = 310
  const paginationHeight = 0
  return windowHeight - headerHeight - paginationHeight
})

const handleResize = () => {
  tableHeight.value = maxHeight.value
}

onMounted(() => {
  tableHeight.value = maxHeight.value
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
})
</script>
<template>
  <div class="app-container">
    <div class="app">
      <!-- 查询条件组件 -->
      <SelectForm :SelectForm="SelectList" @selectSubmit="selectSubmit" />
    </div>
    <el-card class="box-card">
      <el-button type="primary" v-hasPermi="['order:subcontracting:converter:add']" @click="add">添加</el-button>
      <el-button
        type="primary"
        v-hasPermi="['order:subcontracting:converter:converterReview']"
        :disabled="ExamineDisabled"
        @click="examine"
        >审核</el-button
      >
      <el-button
        type="warning"
        v-hasPermi="['order:subcontracting:converter:reviewSubmit']"
        :disabled="ExamineDisabled"
        @click="subExamine"
        >提交审核</el-button
      >
      <el-button
        type="danger"
        v-hasPermi="['order:subcontracting:converter:frozen']"
        :disabled="ExamineDisabled"
        @click="frozen"
        >冻结加工商</el-button
      >
      <el-button
        type="success"
        v-hasPermi="['order:subcontracting:converter:thaw']"
        :disabled="ExamineDisabled"
        @click="thaw"
        >解冻加工商</el-button
      >
      <el-button
        type="primary"
        v-hasPermi="['order:subcontracting:converter:revoke']"
        :disabled="ExamineDisabled"
        @click="revoke"
        >撤销审核</el-button
      >
      <el-button
        type="danger"
        v-hasPermi="['order:subcontracting:converter:remove']"
        :disabled="DelDisabled"
        @click="del"
        >删除</el-button
      >
      <el-button type="info" v-hasPermi="['order:subcontracting:converter:import']" @click="importShow = true"
        >导入</el-button
      >
      <el-button
        type="info"
        v-hasPermi="['order:subcontracting:converter:export']"
        @click="
          proxy.download(
            '/order/converter-management/converterMessageExport',
            {
              ...query,
              ids: Ids
            },
            '加工商'
          )
        "
        >导出</el-button
      >
      <!-- 表格数据 -->
      <el-table
        class="tableClass"
        v-loading="loading"
        stripe
        border
        :data="TableData"
        @selection-change="handleSelectionChange"
        :height="maxHeight"
      >
        <el-table-column type="selection" width="55" align="center" fixed="left" />
        <el-table-column label="序号" width="70" type="index" />
        <el-table-column label="加工商名称" prop="converterName" width="120" />
        <el-table-column label="审核状态" align="center" width="120">
          <template #default="scope">
            <div>
              <p-tag bgc="#006cb6" text="待提交" v-if="scope.row.auditStatus == 1" />
              <p-tag bgc="#fbc82f" text="待审核" v-else-if="scope.row.auditStatus == 2" />
              <p-tag bgc="#f28e16" text="审核中" v-else-if="scope.row.auditStatus == 3" />
              <p-tag bgc="#43b244" text="启用" v-else-if="scope.row.auditStatus == 4" />
              <p-tag bgc="#ff0000" text="未通过" v-else-if="scope.row.auditStatus == 5" />
              <p-tag bgc="#ff0000" text="已冻结" v-else />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="加工商简称" prop="converterAbbreviation" width="auto" />
        <el-table-column label="加工商编号" prop="converterNum" width="auto" />
        <!-- <el-table-column
          label="所属机构"
          prop="affiliatedOrganizationDict"
          width="auto"
          :show-overflow-tooltip="true"
        /> -->
        <el-table-column label="加工商等级" prop="converterLevelDict" width="auto" />
        <el-table-column label="归属人" prop="ascriptionBy" width="auto" />
        <el-table-column label="联系人" prop="contactsBy" width="80" />
        <el-table-column label="联系方式" prop="contactsInformation" width="auto" />
        <el-table-column label="加工商地址" prop="converterAddress" width="auto" :show-overflow-tooltip="true" />
        <el-table-column label="备注" prop="remark" width="160" :show-overflow-tooltip="true" />
        <el-table-column label="操作" align="center" width="160" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <div>
              <el-link
                type="primary"
                v-hasPermi="['order:subcontracting:converter:edit']"
                v-show="scope.row.auditStatus == 1 || scope.row.auditStatus == 5"
                text="修改"
                @click="edit(scope.row.id)"
              />
              <el-link
                type="primary"
                v-hasPermi="['order:subcontracting:converter:remove']"
                v-show="scope.row.auditStatus == 6"
                text="删除"
                @click="del(scope.row.id)"
              />
              <el-link
                type="primary"
                v-hasPermi="['order:subcontracting:converter:query']"
                text="查看"
                @click="dxamine(scope.row)"
              />
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="query.pageNum"
        v-model:limit="query.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 新增弹窗 -->
    <p-XiaoheDialog :dialogVisible="addIsShow" :title="title" @close="addClose" width="50%">
      <template #body>
        <Form ref="FormOneRef" :disabled="title === '查看'" :data="ruleForm" />
        <div style="width: 100%">
          <div class="Btn" v-if="title !== '查看'">
            <el-button type="primary" :loading="Btnloading" @click="title === '新增' ? addSub() : EditSub()"
              >保存</el-button
            >
            <el-button type="inof" @click="addClose">取消</el-button>
          </div>
        </div>
      </template>
    </p-XiaoheDialog>
    <!-- 审核弹窗 -->
    <p-XiaoheDialog :dialogVisible="examineIsShow" title="审核" @close="examineClose" width="50%">
      <template #body>
        <AuditHistory :auditDoc="rows[0].converterNum || ''" perms="order:subcontracting:converter:converterReview">
          <template #body>
            <Form
              ref="FormOneRef"
              disabled
              :examine="title == '审核'"
              :reviewComments="title == '查看'"
              :data="ruleForm"
            />
            <div class="Btn" v-if="title == '审核'">
              <el-button type="danger" :loading="Btnloading" @click="yesAndNo(2)">不同意</el-button>
              <el-button type="success" :loading="Btnloading" @click="yesAndNo(1)">同意</el-button>
              <el-button type="inof" @click="examineClose">取消</el-button>
            </div>
          </template>
        </AuditHistory>
      </template>
    </p-XiaoheDialog>
    <p-impoer
      v-model:isShow="importShow"
      templateUrl="/order/converter-management/downTemplate"
      importUrl="/order/converter-management/converterMessageImport"
      @close="getList"
    />
  </div>
</template>

<style scoped lang="scss"></style>
